package com.sumainfor.pc.market.service;

import com.sumainfor.common.Constants;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.FieldCheckUtil;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.*;
import com.sumainfor.pc.market.dao.*;
import com.sumainfor.pc.market.feign.EpcFeign.EpcFeign;
import com.sumainfor.pc.market.feign.ZuulFeign.ZuulFeign;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 功能描述:
 * 管家巡房
 *
 * @Auther: zhlu
 * @Date: 2019/3/5 21:19
 * @Description:
 */
@Service
public class HousingPatrolService {
    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(HousingPatrolService.class);

    @Autowired
    HousingPatrolMaaper HousingPatrolMaaper;

    @Autowired
    HousingMapper HousingMapper;

    @Autowired
    HousingPactMapper HousingPactMapper;

    @Autowired
    ViolationMapper ViolationMapper;

    @Autowired
    UtilsMapper utilsMapper;

    @Autowired
    EpcFeign EpcFeign;

    @Autowired
    ZuulFeign ZuulFeign;

    String UUID = null;

    //管家巡房租客违规编号
    String PatVioId = null;

    /**
     * 功能描述:
     * 获取管家巡房列表
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/5 21:20
     */
    public List<Map<String, Object>> getHousingPatrolList(Map<String, Object> params) {
        List<Map<String, Object>> getHousingPatrolList = HousingPatrolMaaper.getHousingPatrolList(params);
        return getHousingPatrolList;
    }

    /**
     * 功能描述:
     * 获取管家巡房列表总数
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/5 21:23
     */
    public Integer getHousingPatrolListCount(Map<String, Object> params) {
        Integer getHousingPatrolListCount = HousingPatrolMaaper.getHousingPatrolListCount(params);
        return getHousingPatrolListCount;
    }

    /**
     * 功能描述:
     * 获取本月巡房列表资料
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/6 14:10
     */
    public Map<String, Object> getHousingPatrolData(Map<String, Object> params) {
        Map<String, Object> getHousingPatrolData = new HashMap<String, Object>();
        //已验收房源总套数
        Integer getHousingAcceptanceCount = HousingMapper.getHousingAcceptanceCount(params);
        //获取已验收房源房间总套数
        Integer getHousingInfoAcceptanceCount = HousingMapper.getHousingInfoAcceptanceCount(params);
        //获取管家本月巡房记录总数
        Integer gerHousingPatrolCount = HousingPatrolMaaper.gerHousingPatrolCount(params);
        //问题房源
        Integer getHousingPatrolListCount = HousingPatrolMaaper.getHousingPatrolListCount(params);
        //占比等于巡房总数/总房间数
        Double Proportion = 0.00;
        if (getHousingAcceptanceCount != 0) {
            Proportion = CompuUtils.div(Double.valueOf(gerHousingPatrolCount), Double.valueOf(getHousingAcceptanceCount), 2);
        }
        log.info("----------------");
        log.info("Proportion", Proportion);
        getHousingPatrolData.put("HousingCount", getHousingAcceptanceCount);//房源总数
        getHousingPatrolData.put("RoomCount", getHousingInfoAcceptanceCount);//房源房间总数
        getHousingPatrolData.put("PatrolCount", gerHousingPatrolCount);//已巡房总数
        getHousingPatrolData.put("Proportion", CompuUtils.mul(Proportion, 100));//占比
        getHousingPatrolData.put("Problem", getHousingPatrolListCount);//问题房源
        return getHousingPatrolData;
    }

    /**
     * 功能描述:
     * 根据房源编号获取巡房资料
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/7 19:28
     */
    public Map<String, Object> getPatrolHousginMap(Map<String, Object> params) {
        //根据房源主编号获取巡房房源资料
        Map<String, Object> getPatrolHousginMap = HousingMapper.getPatrolHousginMap(params);
        //根据房源主编号获取巡房房源区域
        List<Map<String, Object>> getPatrolHousingConList = HousingMapper.getPatrolHousingConList(params);
        //根据房源编号获取当前房源签约合同租客资料和签约房源详情
        List<Map<String, Object>> getHousingPactList = HousingPactMapper.getHousingPactList(params);
        getPatrolHousginMap.put("HouConList", getPatrolHousingConList);
        getPatrolHousginMap.put("HouInfoIdList", getHousingPactList);
        return getPatrolHousginMap;
    }

    /**
     * 功能描述:
     * 新增管家巡房记录
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/8 16:20
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean AddPatrol(Map<String, Object> params) throws Exception {
        boolean result = false;
        log.info("params----" + params);
        lock.lock();
        try {
            try {
                //查询巡房主表
                Map<String, Object> uuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                    put("uuid", "PatId");
                    put("database", Constants.DATA_SOURCE_TCMKT);
                    put("surface", "tcmkt_patrol");
                }});
                if (uuid != null) {
                    int number = Integer.valueOf(uuid.get("uuid").toString());
                    UUID = ComUtils.getLocalTrmSeqNum("xf", number);
                } else {
                    UUID = ComUtils.getLocalTrmSeqNum("xf", 0);
                }
                //所有新增处理
                Map<String, Object> commonInsertParms = new HashMap<String, Object>();
                commonInsertParms.put("by", ContextUtils.getUserId());//操作人
                commonInsertParms.put("PatId", UUID);//巡房主编号
                commonInsertParms.put("SysUserId", ContextUtils.getUserId());//巡房管家
                commonInsertParms.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                commonInsertParms.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(commonInsertParms);
                params.put("PatTime", ConvertDateTime.getCurrentTime());
                params.put("PatMonth", ConvertDateTime.getCurrentDateElement(3));
                params.putAll(commonInsertParms);

                //管家设备维修照片
                List<Map<String, Object>> TroubleFileList = (List<Map<String, Object>>) params.get("TroubleFile");
                String TroubleFile = FileSubufferUtils.ListFlieStringUtils(TroubleFileList);

                //管家租客违规照片
                List<Map<String, Object>> ViolationFileList = (List<Map<String, Object>>) params.get("ViolationFile");
                String ViolationFile = FileSubufferUtils.ListFlieStringUtils(ViolationFileList);

                //管家保洁照片
                List<Map<String, Object>> FileList = (List<Map<String, Object>>) params.get("File");
                String File = FileSubufferUtils.ListFlieStringUtils(FileList);

                //管家新增维修工单
                List<Map<String, Object>> repair = (List<Map<String, Object>>) params.get("repair");
                for (Map<String, Object> map : repair) {
                    map.put("PatId", params.get("PatId"));//巡房编号
                    map.put("ComId", params.get("ComId"));//项目编号
                    map.put("RepNotes", params.get("RepNotes"));//备注
                    map.put("TroubleFile", TroubleFile);//图片
                    map.put("MiId", params.get("MiId"));//服务中心
                }
                Map<String, Object> repairMap = new HashMap<String, Object>();
                repairMap.put("repair", repair);
                boolean rep = EpcFeign.AddRepair(repairMap);
                //管家新增维修工单结束
                if (rep) {
                    //新增管家巡房记录
                    HousingPatrolMaaper.AddPatrol(params);

                    //管家巡房租客违规
                    List<Map<String, Object>> violation = (List<Map<String, Object>>) params.get("violation");
                    for (Map<String, Object> map : violation) {
                        if (FieldCheckUtil.isMapFieldNotNull(map, new String[]{"VioId"}) && FieldCheckUtil.isMapFieldNotNull(map, new String[]{"VioInfoId"}) && FieldCheckUtil.isMapFieldNotNull(map, new String[]{"HouInfoId"})) {
                            //查询巡房主表
                            Map<String, Object> patVioId = utilsMapper.getUUID(new HashMap<String, Object>() {{
                                put("uuid", "PatVioId");
                                put("database", Constants.DATA_SOURCE_TCMKT);
                                put("surface", "tcmkt_patrol_violation");
                            }});
                            if (patVioId != null) {
                                int number = Integer.valueOf(patVioId.get("uuid").toString());
                                PatVioId = ComUtils.getLocalTrmSeqNum("xfzk", number);
                            } else {
                                PatVioId = ComUtils.getLocalTrmSeqNum("xfzk", 0);
                            }
                            map.put("PatVioId", PatVioId);
                            map.put("ViolationFile", ViolationFile);
                            map.putAll(commonInsertParms);
                            HousingPatrolMaaper.AddPatrolViolation(map);
                        }
                    }

                    //管家巡房保洁
                    Map<String, Object> Cleaning = (Map<String, Object>) params.get("Cleaning");
                    if (FieldCheckUtil.isMapFieldNotNull(Cleaning, new String[]{"Time"})) {
                        Cleaning.put("File", File);
                        Cleaning.putAll(commonInsertParms);
                        HousingPatrolMaaper.AddPatrolCleaning(Cleaning);
                    }
                    result = true;
                }
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 功能描述:
     * 根据管家巡房主编号获取巡房资料
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/9 12:01
     */
    public Map<String, Object> getPatrol(Map<String, Object> params) {
        //据管家巡房主编号获取巡房资料
        Map<String, Object> getPatrol = HousingPatrolMaaper.getPatrol(params);
        if (getPatrol.get("IfRepair").equals(1) || getPatrol.get("IfRepair").toString() == "1") {
            List<Map<String, Object>> getHousingRepairList = EpcFeign.getHousingRepairList(params);
            if (getHousingRepairList.size() > 0) {
                for (Map<String, Object> map : getHousingRepairList) {
                    map.put("HouConList", HousingMapper.getPatrolHousingConList(new HashMap<String, Object>() {{
                        put("HouId", getPatrol.get("HouId"));
                    }}));
                }
                getPatrol.put("repair", getHousingRepairList);
                getPatrol.put("RepNotes", getHousingRepairList.get(0).get("RepNotes"));
//                log.info("TroubleFile------"+getHousingRepairList.get(0).get("TroubleFile").toString());
                if (StringUtils.isNotBlank(MapUtils.getString(getHousingRepairList.get(0), "TroubleFile"))) {
                    getPatrol.put("TroubleFile", FileSubufferUtils.StringFlieListUtils(getHousingRepairList.get(0).get("TroubleFile").toString()));
                } else {
                    getPatrol.put("TroubleFile", new ArrayList<Map<String, Object>>());
                }

            } else {
                getPatrol.put("repair", new ArrayList<Map<String, Object>>());
                getPatrol.put("RepNotes", null);
                getPatrol.put("TroubleFile", new ArrayList<Map<String, Object>>());
            }
        } else {
            getPatrol.put("repair", new ArrayList<Map<String, Object>>());
            getPatrol.put("RepNotes", null);
            getPatrol.put("TroubleFile", new ArrayList<Map<String, Object>>());
        }
        if (getPatrol.get("IfViolation").equals(1) || getPatrol.get("IfViolation").toString() == "1") {
            //根据管家巡房编号获取租客违规记录
            List<Map<String, Object>> getPatrolViolationList = HousingPatrolMaaper.getPatrolViolationList(getPatrol);
            if (getPatrolViolationList.size() > 0) {
                for (Map<String, Object> map : getPatrolViolationList) {
                    map.put("VioIdList", ViolationMapper.getViolationList(new HashMap<String, Object>() {{
                        put("delfg", 0);
                    }}));
                    map.put("VioInfoIdList", ViolationMapper.getViolationInfoList(new HashMap<String, Object>() {{
                        put("delfg", 0);
                    }}));
                    map.put("HouInfoIdList", HousingPactMapper.getHousingPactList(new HashMap<String, Object>() {{
                        put("delfg", 0);
                        put("FlowStatus", 2);
                        put("HouId", getPatrol.get("HouId"));
                    }}));
                }
                getPatrol.put("violation", getPatrolViolationList);
                if (StringUtils.isNotBlank(MapUtils.getString(getPatrolViolationList.get(0), "ViolationFile"))) {
                    getPatrol.put("ViolationFile", FileSubufferUtils.StringFlieListUtils(getPatrolViolationList.get(0).get("ViolationFile").toString()));
                } else {
                    getPatrol.put("ViolationFile", new ArrayList<Map<String, Object>>());
                }
            }
        } else {
            getPatrol.put("violation", new ArrayList<Map<String, Object>>());
            getPatrol.put("ViolationFile", new ArrayList<Map<String, Object>>());
        }
        if (getPatrol.get("IfCleaning").equals(1) || getPatrol.get("IfCleaning").toString() == "1") {
            //根据管家巡房编号获取保洁服务
            Map<String, Object> getPatrolCleaningMap = HousingPatrolMaaper.getPatrolCleaningMap(getPatrol);
            getPatrol.put("Cleaning", getPatrolCleaningMap);
            if (StringUtils.isNotBlank(MapUtils.getString(getPatrolCleaningMap, "File"))) {
                getPatrol.put("File", FileSubufferUtils.StringFlieListUtils(getPatrolCleaningMap.get("File").toString()));
            } else {
                getPatrol.put("File", new ArrayList<Map<String, Object>>());
            }

        } else {
            getPatrol.put("Cleaning", new HashMap<String, Object>());
            getPatrol.put("File", new ArrayList<Map<String, Object>>());
        }
        getPatrol.put("IfRepair", getPatrol.get("IfRepair").toString());
        getPatrol.put("IfViolation", getPatrol.get("IfViolation").toString());
        getPatrol.put("IfCleaning", getPatrol.get("IfCleaning").toString());
        return getPatrol;
    }

    /**
     * 功能描述:
     * 根据管家巡房主编号和租客违规编号修改租客违规和保洁违规
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/9 17:56
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean UpdatePatrol(Map<String, Object> params) {
        boolean result = false;
        //所有修改处理
        Map<String, Object> commonUpdateParms = new HashMap<String, Object>();
        commonUpdateParms.put("by", ContextUtils.getUserId());//操作人
        commonUpdateParms.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
        commonUpdateParms.put("fnc",
                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
        ParamsCommon.commonUpdateParms(commonUpdateParms);
        try {
            List<Map<String, Object>> violation = (List<Map<String, Object>>) params.get("violation");
            if (violation.size() > 0) {
                for (Map<String, Object> map : violation) {
                    map.putAll(commonUpdateParms);
                    //修改租客违规
                    HousingPatrolMaaper.UpdateViolation(map);
                }
            }

            Map<String, Object> Cleaning = (Map<String, Object>) params.get("Cleaning");
            Cleaning.putAll(commonUpdateParms);
            Cleaning.put("PatId", params.get("PatId"));
            //修改保洁违规
            HousingPatrolMaaper.UpdateCleaning(Cleaning);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    /**
     * 功能描述:
     * 根据房源主编号获取当前房源历史租客违规列表
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/5/23 17:24
     */
    public List<Map<String, Object>> getPatrolHousingViolationList(Map<String, Object> params) {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        //当前房源历史租客违规
        List<Map<String, Object>> HousingViolationList = HousingPatrolMaaper.getPatrolHousingViolationList(params);

        //获取所有的后台用户资料
        JsonResult jsonResult = ZuulFeign.getAllUserIdAndName();
        List<Map<String, Object>> getAllUserIdAndName = (List<Map<String, Object>>) jsonResult.getResult();
        //合并
        result = ListMapMergeUtil.ListMergeUtils(HousingViolationList, getAllUserIdAndName, "userId");
        return result;
    }

    /**
     * 功能描述:
     * 根据房源主编号获取当前房源历史租客违规总数
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/5/23 17:29
     */
    public Integer getPatrolHousingViolationCount(Map<String, Object> params) {
        return HousingPatrolMaaper.getPatrolHousingViolationCount(params);
    }

    /**
     * 功能描述:
     * 根据房源主编号获取当前房源历史保洁违规列表
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/5/23 17:24
     */
    public List<Map<String, Object>> getPatrolHousingCleaningList(Map<String, Object> params) {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        //当前房源历史保洁违规
        List<Map<String, Object>> HousingViolationList = HousingPatrolMaaper.getPatrolHousingCleaningList(params);

        //获取所有的后台用户资料
        JsonResult jsonResult = ZuulFeign.getAllUserIdAndName();
        List<Map<String, Object>> getAllUserIdAndName = (List<Map<String, Object>>) jsonResult.getResult();
        //合并
        result = ListMapMergeUtil.ListMergeUtils(HousingViolationList, getAllUserIdAndName, "userId");
        return result;
    }

    /**
     * 功能描述:
     * 根据房源主编号获取当前房源历史保洁违规总数
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/5/23 17:29
     */
    public Integer getPatrolHousingCleaningCount(Map<String, Object> params) {
        return HousingPatrolMaaper.getPatrolHousingCleaningCount(params);
    }

    /**
     * 功能描述:
     * 历史巡房保洁，根据巡房主编号修改保洁状态
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/5/24 14:29
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean UpdateCleaning(Map<String, Object> params) {
        boolean result = false;
        //所有修改处理
        Map<String, Object> commonUpdateParms = new HashMap<String, Object>();
        commonUpdateParms.put("by", ContextUtils.getUserId());//操作人
        commonUpdateParms.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
        commonUpdateParms.put("fnc",
                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
        ParamsCommon.commonUpdateParms(commonUpdateParms);
        try {
            params.putAll(commonUpdateParms);
            //修改保洁违规
            HousingPatrolMaaper.UpdateCleaning(params);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    /**
     * 功能描述:
     * 根据巡房记录编号获取租客违规列表
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/5/24 15:54
     */
    public List<Map<String, Object>> getPatrolHousingViolationInfoList(Map<String, Object> params) {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> ViolationInfoList = HousingPatrolMaaper.getPatrolHousingViolationInfoList(params);
        //获取所有的后台用户资料
        JsonResult jsonResult = ZuulFeign.getAllUserIdAndName();
        List<Map<String, Object>> getAllUserIdAndName = (List<Map<String, Object>>) jsonResult.getResult();
        //合并
        result = ListMapMergeUtil.ListMergeUtils(ViolationInfoList, getAllUserIdAndName, "userId");
        return result;
    }

    /**
     * 功能描述:
     * 根据巡房记录编号获取租客违规列表总数
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/5/24 15:55
     */
    public Integer getPatrolHousingViolationInfoCount(Map<String, Object> params) {
        return HousingPatrolMaaper.getPatrolHousingViolationInfoCount(params);
    }

    /**
     * 功能描述:
     * 根据违规记录编号修改某一个租客违规
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/5/24 16:17
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean UpdateViolation(Map<String, Object> params) {
        boolean result = false;
        //所有修改处理
        Map<String, Object> commonUpdateParms = new HashMap<String, Object>();
        commonUpdateParms.put("by", ContextUtils.getUserId());//操作人
        commonUpdateParms.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
        commonUpdateParms.put("fnc",
                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
        ParamsCommon.commonUpdateParms(commonUpdateParms);
        try {
            params.putAll(commonUpdateParms);
            //修改租客违规
            HousingPatrolMaaper.UpdateViolation(params);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

}
